﻿function SocketHelper(params) {
   var options = $.extend({}, {
        uri: "ws://" + window.location.host + "/socket/connect",
       Received: function (result) {
        
          
       },//接收事件
        ReceiverId: "" //接收人
   }, params);
   var socket;//对象
   var SenderId = params.SenderId;//发送人
   var SenderName = params.SenderName;//发送人
    Connect = function () {
        // this.uri = uri;
        this.socket = new WebSocket(options.uri);
        this.socket.onopen = function (e) { _self.Open(e) };
        var _self = this;
        this.socket.onmessage = function (e) { _self.Received(e); };
        this.socket.onerror = function (e) { _self.Error(e); };
    };
    Send = function (ReceiverId, message) {
        var sendData = { "SenderId": SenderId, "SenderName": SenderName, "ReceiverId": ReceiverId, "MessageType": "text", "Content": message };
        try {
            this.socket.send(JSON.stringify(sendData));
        } catch (e) {
            this.Connect();

        }
        
    };
    Open = function (e) {
        this.Send("Service","连接");
        console.log("socket opened", e);
    };
    Close = function (e) {
        this.socket.close();
        console.log("socket closed", e);
    };
    Received = function (e) {
     
        var result = eval("(" + e.data + ")");
        if (options.Received) {
       
            options.Received(result);
        }
        if (result.SenderId == "Service" && result.Content == "open")
        {
            SenderId = result.ReceiverId;
            if (SenderName == "")
            {
                SenderName = SenderId;
            }
        }
    };
    Error = function (e) {
        console.log("Error: " + e.data);
    }
    this.Connect();
    return this;
}
///Signalr
function SignalrHelper(options) {
    Object.defineProperty(WebSocket, 'OPEN', { value: 1, });
    var SenderId = options.SenderId;//发送人
    var SenderName = options.SenderName;//发送人
    var mysignalr = new signalR.HubConnectionBuilder().withUrl("/mysignalr")
        .configureLogging(signalR.LogLevel.Information)
        .build();
    mysignalr.on("ReceiveMessage", (result, message) => {
        if (result.ReceiverId == result.Content) {
            //SenderId = result.ReceiverId;
            if (SenderName == "") {
                SenderName = SenderId;
            }
        }
        else {
            if (options.Received) {
                options.Received(result);
            }
           
        }
    });
    Send = function (ReceiverId, message) {
        mysignalr.invoke('SendMessage', { "SenderId": SenderId, "SenderName": SenderName, "ReceiverId": ReceiverId, "MessageType": "text", "Content": message });

    };
    mysignalr.start().catch(err => console.log(err.toString()));
    return this;
}
